package com.anibo.mathtricks;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import edu.hws.jcm.data.Expression;
import edu.hws.jcm.data.Parser;
import edu.hws.jcm.data.Variable;

public class Deriver extends Activity {
    private Dialog aboutDialog;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        createAboutDialog();
        
        Button button = (Button) this.findViewById(R.id.Button01);
        
        View.OnClickListener clickListener = new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String s = ((EditText) Deriver.this.findViewById(R.id.EditText01)).getText().toString();
				((EditText) Deriver.this.findViewById(R.id.EditText02)).setText(calcDerive(s));
			}
		};
		
		button.setOnClickListener(clickListener);
    }
    
    private void createAboutDialog() {
  /*  	Context mContext = getApplicationContext();
    	aboutDialog = new Dialog(mContext);

    	aboutDialog.setContentView(R.layout.about);
    	aboutDialog.setTitle("Custom Dialog");
*/    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.
    	    setTitle(R.string.about).
    	    setMessage( R.string.about_us).
    	    setCancelable(true).
    	    setNeutralButton("OK", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	                dialog.cancel();
    	           }
    	       });
    	aboutDialog = builder.create();

    }
    
    public boolean onCreateOptionsMenu(android.view.Menu menu) {
    	   MenuInflater inflater = getMenuInflater();
    	    inflater.inflate(R.menu.main_menu, menu);
    	    return true;
    }
    
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        switch (item.getItemId()) {
       case R.id.about:
        	aboutDialog.show();
            return true;
       case R.id.quit:
            	this.finish();
                return true;
        }
        return false;
    }
    
    String calcDerive(String s) {
    	try {
	        Parser parser = new Parser(Parser.STANDARD_FUNCTIONS | Parser.OPTIONAL_STARS | Parser.OPTIONAL_PARENS);
	        Variable xVar = new Variable("x");
	        parser.add(xVar);
	        Expression e = parser.parse(s);
	        
	        e = e.derivative(xVar); 
	        return e.toString();
    	} catch (Exception e) {
    		return e.getMessage();
    	}
    }
    
}